<!DOCTYPE html>
<html class="writer-html5" lang="en" >
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>ib_insync.util &mdash; ib_insync 0.9.70 documentation</title>
      <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
      <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
    <link rel="canonical" href="https://ib_insync.readthedocs.io_modules/ib_insync/util.html"/>
  
        <script data-url_root="../../" id="documentation_options" src="../../_static/documentation_options.js"></script>
        <script src="../../_static/jquery.js"></script>
        <script src="../../_static/underscore.js"></script>
        <script src="../../_static/doctools.js"></script>
    <script src="../../_static/js/theme.js"></script>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" /> 
</head>

<body class="wy-body-for-nav"> 
  <div class="wy-grid-for-nav">
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
            <a href="../../index.html" class="icon icon-home"> ib_insync
          </a>
              <div class="version">
                0.9
              </div>
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>
        </div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
              <ul>
<li class="toctree-l1"><a class="reference internal" href="../../readme.html">Introduction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../api.html">API docs</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notebooks.html">Notebooks</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../recipes.html">Code recipes</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../code.html">Source code</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../changelog.html">Changelog</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../links.html">Links</a></li>
</ul>

        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" >
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../index.html">ib_insync</a>
      </nav>

      <div class="wy-nav-content">
        <div class="rst-content">
          <div role="navigation" aria-label="Page navigation">
  <ul class="wy-breadcrumbs">
      <li><a href="../../index.html" class="icon icon-home"></a> &raquo;</li>
          <li><a href="../index.html">Module code</a> &raquo;</li>
      <li>ib_insync.util</li>
      <li class="wy-breadcrumbs-aside">
      </li>
  </ul>
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
             
  <h1>Source code for ib_insync.util</h1><div class="highlight"><pre>
<span></span><span class="sd">&quot;&quot;&quot;Utilities.&quot;&quot;&quot;</span>

<span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">math</span>
<span class="kn">import</span> <span class="nn">signal</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">fields</span><span class="p">,</span> <span class="n">is_dataclass</span>
<span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">date</span><span class="p">,</span> <span class="n">datetime</span><span class="p">,</span> <span class="n">time</span> <span class="k">as</span> <span class="n">time_</span><span class="p">,</span> <span class="n">timedelta</span><span class="p">,</span> <span class="n">timezone</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">AsyncIterator</span><span class="p">,</span> <span class="n">Awaitable</span><span class="p">,</span> <span class="n">Callable</span><span class="p">,</span> <span class="n">Iterator</span><span class="p">,</span> <span class="n">List</span><span class="p">,</span> <span class="n">Union</span>

<span class="kn">import</span> <span class="nn">eventkit</span> <span class="k">as</span> <span class="nn">ev</span>

<span class="n">globalErrorEvent</span> <span class="o">=</span> <span class="n">ev</span><span class="o">.</span><span class="n">Event</span><span class="p">()</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">Event to emit global exceptions.</span>
<span class="sd">&quot;&quot;&quot;</span>

<span class="n">EPOCH</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="mi">1970</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">tzinfo</span><span class="o">=</span><span class="n">timezone</span><span class="o">.</span><span class="n">utc</span><span class="p">)</span>
<span class="n">UNSET_INTEGER</span> <span class="o">=</span> <span class="mi">2</span> <span class="o">**</span> <span class="mi">31</span> <span class="o">-</span> <span class="mi">1</span>
<span class="n">UNSET_DOUBLE</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">float_info</span><span class="o">.</span><span class="n">max</span>


<div class="viewcode-block" id="df"><a class="viewcode-back" href="../../api.html#ib_insync.ib.df">[docs]</a><span class="k">def</span> <span class="nf">df</span><span class="p">(</span><span class="n">objs</span><span class="p">,</span> <span class="n">labels</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Create pandas DataFrame from the sequence of same-type objects.</span>

<span class="sd">    Args:</span>
<span class="sd">      labels: If supplied, retain only the given labels and drop the rest.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
    <span class="kn">from</span> <span class="nn">.objects</span> <span class="kn">import</span> <span class="n">DynamicObject</span>
    <span class="k">if</span> <span class="n">objs</span><span class="p">:</span>
        <span class="n">objs</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">objs</span><span class="p">)</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="n">objs</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">if</span> <span class="n">is_dataclass</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
            <span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="o">.</span><span class="n">from_records</span><span class="p">(</span><span class="n">dataclassAsTuple</span><span class="p">(</span><span class="n">o</span><span class="p">)</span> <span class="k">for</span> <span class="n">o</span> <span class="ow">in</span> <span class="n">objs</span><span class="p">)</span>
            <span class="n">df</span><span class="o">.</span><span class="n">columns</span> <span class="o">=</span> <span class="p">[</span><span class="n">field</span><span class="o">.</span><span class="n">name</span> <span class="k">for</span> <span class="n">field</span> <span class="ow">in</span> <span class="n">fields</span><span class="p">(</span><span class="n">obj</span><span class="p">)]</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">DynamicObject</span><span class="p">):</span>
            <span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="o">.</span><span class="n">from_records</span><span class="p">(</span><span class="n">o</span><span class="o">.</span><span class="vm">__dict__</span> <span class="k">for</span> <span class="n">o</span> <span class="ow">in</span> <span class="n">objs</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="o">.</span><span class="n">from_records</span><span class="p">(</span><span class="n">objs</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">tuple</span><span class="p">):</span>
            <span class="n">_fields</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="s1">&#39;_fields&#39;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">_fields</span><span class="p">:</span>
                <span class="c1"># assume it&#39;s a namedtuple</span>
                <span class="n">df</span><span class="o">.</span><span class="n">columns</span> <span class="o">=</span> <span class="n">_fields</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">df</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="k">if</span> <span class="n">labels</span><span class="p">:</span>
        <span class="n">exclude</span> <span class="o">=</span> <span class="p">[</span><span class="n">label</span> <span class="k">for</span> <span class="n">label</span> <span class="ow">in</span> <span class="n">df</span> <span class="k">if</span> <span class="n">label</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">labels</span><span class="p">]</span>
        <span class="n">df</span> <span class="o">=</span> <span class="n">df</span><span class="o">.</span><span class="n">drop</span><span class="p">(</span><span class="n">exclude</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">df</span></div>


<div class="viewcode-block" id="dataclassAsDict"><a class="viewcode-back" href="../../api.html#ib_insync.ib.dataclassAsDict">[docs]</a><span class="k">def</span> <span class="nf">dataclassAsDict</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">dict</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Return dataclass values as ``dict``.</span>
<span class="sd">    This is a non-recursive variant of ``dataclasses.asdict``.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">is_dataclass</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
        <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Object </span><span class="si">{</span><span class="n">obj</span><span class="si">}</span><span class="s1"> is not a dataclass&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">{</span><span class="n">field</span><span class="o">.</span><span class="n">name</span><span class="p">:</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">field</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> <span class="k">for</span> <span class="n">field</span> <span class="ow">in</span> <span class="n">fields</span><span class="p">(</span><span class="n">obj</span><span class="p">)}</span></div>


<div class="viewcode-block" id="dataclassAsTuple"><a class="viewcode-back" href="../../api.html#ib_insync.ib.dataclassAsTuple">[docs]</a><span class="k">def</span> <span class="nf">dataclassAsTuple</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">tuple</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Return dataclass values as ``tuple``.</span>
<span class="sd">    This is a non-recursive variant of ``dataclasses.astuple``.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">is_dataclass</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
        <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Object </span><span class="si">{</span><span class="n">obj</span><span class="si">}</span><span class="s1"> is not a dataclass&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">field</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> <span class="k">for</span> <span class="n">field</span> <span class="ow">in</span> <span class="n">fields</span><span class="p">(</span><span class="n">obj</span><span class="p">))</span></div>


<div class="viewcode-block" id="dataclassNonDefaults"><a class="viewcode-back" href="../../api.html#ib_insync.ib.dataclassNonDefaults">[docs]</a><span class="k">def</span> <span class="nf">dataclassNonDefaults</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">dict</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    For a ``dataclass`` instance get the fields that are different from the</span>
<span class="sd">    default values and return as ``dict``.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">is_dataclass</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
        <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Object </span><span class="si">{</span><span class="n">obj</span><span class="si">}</span><span class="s1"> is not a dataclass&#39;</span><span class="p">)</span>
    <span class="n">values</span> <span class="o">=</span> <span class="p">[</span><span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">field</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> <span class="k">for</span> <span class="n">field</span> <span class="ow">in</span> <span class="n">fields</span><span class="p">(</span><span class="n">obj</span><span class="p">)]</span>
    <span class="k">return</span> <span class="p">{</span>
        <span class="n">field</span><span class="o">.</span><span class="n">name</span><span class="p">:</span> <span class="n">value</span> <span class="k">for</span> <span class="n">field</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">fields</span><span class="p">(</span><span class="n">obj</span><span class="p">),</span> <span class="n">values</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">value</span> <span class="o">!=</span> <span class="n">field</span><span class="o">.</span><span class="n">default</span>
        <span class="ow">and</span> <span class="n">value</span> <span class="o">==</span> <span class="n">value</span>
        <span class="ow">and</span> <span class="ow">not</span> <span class="p">(</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="nb">list</span><span class="p">)</span> <span class="ow">and</span> <span class="n">value</span> <span class="o">==</span> <span class="p">[])}</span></div>


<div class="viewcode-block" id="dataclassUpdate"><a class="viewcode-back" href="../../api.html#ib_insync.ib.dataclassUpdate">[docs]</a><span class="k">def</span> <span class="nf">dataclassUpdate</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="o">*</span><span class="n">srcObjs</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">object</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Update fields of the given ``dataclass`` object from zero or more</span>
<span class="sd">    ``dataclass`` source objects and/or from keyword arguments.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">is_dataclass</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
        <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Object </span><span class="si">{</span><span class="n">obj</span><span class="si">}</span><span class="s1"> is not a dataclass&#39;</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">srcObj</span> <span class="ow">in</span> <span class="n">srcObjs</span><span class="p">:</span>
        <span class="n">obj</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">dataclassAsDict</span><span class="p">(</span><span class="n">srcObj</span><span class="p">))</span>
    <span class="n">obj</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">obj</span></div>


<div class="viewcode-block" id="dataclassRepr"><a class="viewcode-back" href="../../api.html#ib_insync.ib.dataclassRepr">[docs]</a><span class="k">def</span> <span class="nf">dataclassRepr</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Provide a culled representation of the given ``dataclass`` instance,</span>
<span class="sd">    showing only the fields with a non-default value.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">attrs</span> <span class="o">=</span> <span class="n">dataclassNonDefaults</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
    <span class="n">clsName</span> <span class="o">=</span> <span class="n">obj</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__qualname__</span>
    <span class="n">kwargs</span> <span class="o">=</span> <span class="s1">&#39;, &#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">k</span><span class="si">}</span><span class="s1">=</span><span class="si">{</span><span class="n">v</span><span class="si">!r}</span><span class="s1">&#39;</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">attrs</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
    <span class="k">return</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">clsName</span><span class="si">}</span><span class="s1">(</span><span class="si">{</span><span class="n">kwargs</span><span class="si">}</span><span class="s1">)&#39;</span></div>


<div class="viewcode-block" id="isnamedtupleinstance"><a class="viewcode-back" href="../../api.html#ib_insync.ib.isnamedtupleinstance">[docs]</a><span class="k">def</span> <span class="nf">isnamedtupleinstance</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;From https://stackoverflow.com/a/2166841/6067848&quot;&quot;&quot;</span>
    <span class="n">t</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
    <span class="n">b</span> <span class="o">=</span> <span class="n">t</span><span class="o">.</span><span class="vm">__bases__</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">b</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">1</span> <span class="ow">or</span> <span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">!=</span> <span class="nb">tuple</span><span class="p">:</span>
        <span class="k">return</span> <span class="kc">False</span>
    <span class="n">f</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="s1">&#39;_fields&#39;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="nb">tuple</span><span class="p">):</span>
        <span class="k">return</span> <span class="kc">False</span>
    <span class="k">return</span> <span class="nb">all</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="o">==</span> <span class="nb">str</span> <span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="n">f</span><span class="p">)</span></div>


<div class="viewcode-block" id="tree"><a class="viewcode-back" href="../../api.html#ib_insync.ib.tree">[docs]</a><span class="k">def</span> <span class="nf">tree</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Convert object to a tree of lists, dicts and simple values.</span>
<span class="sd">    The result can be serialized to JSON.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="p">(</span><span class="nb">bool</span><span class="p">,</span> <span class="nb">int</span><span class="p">,</span> <span class="nb">float</span><span class="p">,</span> <span class="nb">str</span><span class="p">,</span> <span class="nb">bytes</span><span class="p">)):</span>
        <span class="k">return</span> <span class="n">obj</span>
    <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="p">(</span><span class="n">date</span><span class="p">,</span> <span class="n">time_</span><span class="p">)):</span>
        <span class="k">return</span> <span class="n">obj</span><span class="o">.</span><span class="n">isoformat</span><span class="p">()</span>
    <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">{</span><span class="n">k</span><span class="p">:</span> <span class="n">tree</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">obj</span><span class="o">.</span><span class="n">items</span><span class="p">()}</span>
    <span class="k">elif</span> <span class="n">isnamedtupleinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">{</span><span class="n">f</span><span class="p">:</span> <span class="n">tree</span><span class="p">(</span><span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">f</span><span class="p">))</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">obj</span><span class="o">.</span><span class="n">_fields</span><span class="p">}</span>
    <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="p">(</span><span class="nb">list</span><span class="p">,</span> <span class="nb">tuple</span><span class="p">,</span> <span class="nb">set</span><span class="p">)):</span>
        <span class="k">return</span> <span class="p">[</span><span class="n">tree</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">obj</span><span class="p">]</span>
    <span class="k">elif</span> <span class="n">is_dataclass</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">{</span><span class="n">obj</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__qualname__</span><span class="p">:</span> <span class="n">tree</span><span class="p">(</span><span class="n">dataclassNonDefaults</span><span class="p">(</span><span class="n">obj</span><span class="p">))}</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span></div>


<div class="viewcode-block" id="barplot"><a class="viewcode-back" href="../../api.html#ib_insync.ib.barplot">[docs]</a><span class="k">def</span> <span class="nf">barplot</span><span class="p">(</span><span class="n">bars</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">upColor</span><span class="o">=</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="n">downColor</span><span class="o">=</span><span class="s1">&#39;red&#39;</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Create candlestick plot for the given bars. The bars can be given as</span>
<span class="sd">    a DataFrame or as a list of bar objects.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
    <span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
    <span class="kn">from</span> <span class="nn">matplotlib.lines</span> <span class="kn">import</span> <span class="n">Line2D</span>
    <span class="kn">from</span> <span class="nn">matplotlib.patches</span> <span class="kn">import</span> <span class="n">Rectangle</span>

    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">bars</span><span class="p">,</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">):</span>
        <span class="n">ohlcTups</span> <span class="o">=</span> <span class="p">[</span>
            <span class="nb">tuple</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">bars</span><span class="p">[[</span><span class="s1">&#39;open&#39;</span><span class="p">,</span> <span class="s1">&#39;high&#39;</span><span class="p">,</span> <span class="s1">&#39;low&#39;</span><span class="p">,</span> <span class="s1">&#39;close&#39;</span><span class="p">]]</span><span class="o">.</span><span class="n">values</span><span class="p">]</span>
    <span class="k">elif</span> <span class="n">bars</span> <span class="ow">and</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">bars</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="s1">&#39;open_&#39;</span><span class="p">):</span>
        <span class="n">ohlcTups</span> <span class="o">=</span> <span class="p">[(</span><span class="n">b</span><span class="o">.</span><span class="n">open_</span><span class="p">,</span> <span class="n">b</span><span class="o">.</span><span class="n">high</span><span class="p">,</span> <span class="n">b</span><span class="o">.</span><span class="n">low</span><span class="p">,</span> <span class="n">b</span><span class="o">.</span><span class="n">close</span><span class="p">)</span> <span class="k">for</span> <span class="n">b</span> <span class="ow">in</span> <span class="n">bars</span><span class="p">]</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">ohlcTups</span> <span class="o">=</span> <span class="p">[(</span><span class="n">b</span><span class="o">.</span><span class="n">open</span><span class="p">,</span> <span class="n">b</span><span class="o">.</span><span class="n">high</span><span class="p">,</span> <span class="n">b</span><span class="o">.</span><span class="n">low</span><span class="p">,</span> <span class="n">b</span><span class="o">.</span><span class="n">close</span><span class="p">)</span> <span class="k">for</span> <span class="n">b</span> <span class="ow">in</span> <span class="n">bars</span><span class="p">]</span>

    <span class="n">fig</span><span class="p">,</span> <span class="n">ax</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">()</span>
    <span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="n">title</span><span class="p">)</span>
    <span class="n">ax</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
    <span class="n">fig</span><span class="o">.</span><span class="n">set_size_inches</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">n</span><span class="p">,</span> <span class="p">(</span><span class="n">open_</span><span class="p">,</span> <span class="n">high</span><span class="p">,</span> <span class="n">low</span><span class="p">,</span> <span class="n">close</span><span class="p">)</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">ohlcTups</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">close</span> <span class="o">&gt;=</span> <span class="n">open_</span><span class="p">:</span>
            <span class="n">color</span> <span class="o">=</span> <span class="n">upColor</span>
            <span class="n">bodyHi</span><span class="p">,</span> <span class="n">bodyLo</span> <span class="o">=</span> <span class="n">close</span><span class="p">,</span> <span class="n">open_</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">color</span> <span class="o">=</span> <span class="n">downColor</span>
            <span class="n">bodyHi</span><span class="p">,</span> <span class="n">bodyLo</span> <span class="o">=</span> <span class="n">open_</span><span class="p">,</span> <span class="n">close</span>
        <span class="n">line</span> <span class="o">=</span> <span class="n">Line2D</span><span class="p">(</span>
            <span class="n">xdata</span><span class="o">=</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">n</span><span class="p">),</span>
            <span class="n">ydata</span><span class="o">=</span><span class="p">(</span><span class="n">low</span><span class="p">,</span> <span class="n">bodyLo</span><span class="p">),</span>
            <span class="n">color</span><span class="o">=</span><span class="n">color</span><span class="p">,</span>
            <span class="n">linewidth</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
        <span class="n">ax</span><span class="o">.</span><span class="n">add_line</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
        <span class="n">line</span> <span class="o">=</span> <span class="n">Line2D</span><span class="p">(</span>
            <span class="n">xdata</span><span class="o">=</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">n</span><span class="p">),</span>
            <span class="n">ydata</span><span class="o">=</span><span class="p">(</span><span class="n">high</span><span class="p">,</span> <span class="n">bodyHi</span><span class="p">),</span>
            <span class="n">color</span><span class="o">=</span><span class="n">color</span><span class="p">,</span>
            <span class="n">linewidth</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
        <span class="n">ax</span><span class="o">.</span><span class="n">add_line</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
        <span class="n">rect</span> <span class="o">=</span> <span class="n">Rectangle</span><span class="p">(</span>
            <span class="n">xy</span><span class="o">=</span><span class="p">(</span><span class="n">n</span> <span class="o">-</span> <span class="mf">0.3</span><span class="p">,</span> <span class="n">bodyLo</span><span class="p">),</span>
            <span class="n">width</span><span class="o">=</span><span class="mf">0.6</span><span class="p">,</span>
            <span class="n">height</span><span class="o">=</span><span class="n">bodyHi</span> <span class="o">-</span> <span class="n">bodyLo</span><span class="p">,</span>
            <span class="n">edgecolor</span><span class="o">=</span><span class="n">color</span><span class="p">,</span>
            <span class="n">facecolor</span><span class="o">=</span><span class="n">color</span><span class="p">,</span>
            <span class="n">alpha</span><span class="o">=</span><span class="mf">0.4</span><span class="p">,</span>
            <span class="n">antialiased</span><span class="o">=</span><span class="kc">True</span>
        <span class="p">)</span>
        <span class="n">ax</span><span class="o">.</span><span class="n">add_patch</span><span class="p">(</span><span class="n">rect</span><span class="p">)</span>

    <span class="n">ax</span><span class="o">.</span><span class="n">autoscale_view</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">fig</span></div>


<div class="viewcode-block" id="allowCtrlC"><a class="viewcode-back" href="../../api.html#ib_insync.ib.allowCtrlC">[docs]</a><span class="k">def</span> <span class="nf">allowCtrlC</span><span class="p">():</span>
    <span class="sd">&quot;&quot;&quot;Allow Control-C to end program.&quot;&quot;&quot;</span>
    <span class="n">signal</span><span class="o">.</span><span class="n">signal</span><span class="p">(</span><span class="n">signal</span><span class="o">.</span><span class="n">SIGINT</span><span class="p">,</span> <span class="n">signal</span><span class="o">.</span><span class="n">SIG_DFL</span><span class="p">)</span></div>


<div class="viewcode-block" id="logToFile"><a class="viewcode-back" href="../../api.html#ib_insync.ib.logToFile">[docs]</a><span class="k">def</span> <span class="nf">logToFile</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Create a log handler that logs to the given file.&quot;&quot;&quot;</span>
    <span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">logger</span><span class="o">.</span><span class="n">handlers</span><span class="p">:</span>
        <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;ib_insync&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">level</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">level</span><span class="p">)</span>
    <span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span>
        <span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(name)s</span><span class="s1"> </span><span class="si">%(levelname)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">handler</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
    <span class="n">handler</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span></div>


<div class="viewcode-block" id="logToConsole"><a class="viewcode-back" href="../../api.html#ib_insync.ib.logToConsole">[docs]</a><span class="k">def</span> <span class="nf">logToConsole</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Create a log handler that logs to the console.&quot;&quot;&quot;</span>
    <span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">()</span>
    <span class="n">stdHandlers</span> <span class="o">=</span> <span class="p">[</span>
        <span class="n">h</span> <span class="k">for</span> <span class="n">h</span> <span class="ow">in</span> <span class="n">logger</span><span class="o">.</span><span class="n">handlers</span>
        <span class="k">if</span> <span class="nb">type</span><span class="p">(</span><span class="n">h</span><span class="p">)</span> <span class="ow">is</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span> <span class="ow">and</span> <span class="n">h</span><span class="o">.</span><span class="n">stream</span> <span class="ow">is</span> <span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">]</span>
    <span class="k">if</span> <span class="n">stdHandlers</span><span class="p">:</span>
        <span class="c1"># if a standard stream handler already exists, use it and</span>
        <span class="c1"># set the log level for the ib_insync namespace only</span>
        <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;ib_insync&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">level</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="c1"># else create a new handler</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">level</span><span class="p">)</span>
        <span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span>
            <span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(name)s</span><span class="s1"> </span><span class="si">%(levelname)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="n">handler</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
        <span class="n">handler</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span></div>


<div class="viewcode-block" id="isNan"><a class="viewcode-back" href="../../api.html#ib_insync.ib.isNan">[docs]</a><span class="k">def</span> <span class="nf">isNan</span><span class="p">(</span><span class="n">x</span><span class="p">:</span> <span class="nb">float</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;Not a number test.&quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">x</span> <span class="o">!=</span> <span class="n">x</span></div>


<div class="viewcode-block" id="formatSI"><a class="viewcode-back" href="../../api.html#ib_insync.ib.formatSI">[docs]</a><span class="k">def</span> <span class="nf">formatSI</span><span class="p">(</span><span class="n">n</span><span class="p">:</span> <span class="nb">float</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;Format the integer or float n to 3 significant digits + SI prefix.&quot;&quot;&quot;</span>
    <span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="k">if</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">n</span> <span class="o">=</span> <span class="o">-</span><span class="n">n</span>
        <span class="n">s</span> <span class="o">+=</span> <span class="s1">&#39;-&#39;</span>
    <span class="k">if</span> <span class="nb">type</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="ow">is</span> <span class="nb">int</span> <span class="ow">and</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39; &#39;</span>
    <span class="k">elif</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="mf">1e-22</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;0.00 &#39;</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">assert</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="mf">9.99e26</span>
        <span class="n">log</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">floor</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">n</span><span class="p">)))</span>
        <span class="n">i</span><span class="p">,</span> <span class="n">j</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="n">log</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">_try</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">):</span>
            <span class="n">templ</span> <span class="o">=</span> <span class="s1">&#39;%.</span><span class="si">{}</span><span class="s1">f&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">2</span> <span class="o">-</span> <span class="n">j</span><span class="p">)</span>
            <span class="n">val</span> <span class="o">=</span> <span class="n">templ</span> <span class="o">%</span> <span class="p">(</span><span class="n">n</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">**</span> <span class="p">(</span><span class="o">-</span><span class="mi">3</span> <span class="o">*</span> <span class="n">i</span><span class="p">))</span>
            <span class="k">if</span> <span class="n">val</span> <span class="o">!=</span> <span class="s1">&#39;1000&#39;</span><span class="p">:</span>
                <span class="k">break</span>
            <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="n">j</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="n">s</span> <span class="o">+=</span> <span class="n">val</span> <span class="o">+</span> <span class="s1">&#39; &#39;</span>
        <span class="k">if</span> <span class="n">i</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
            <span class="n">s</span> <span class="o">+=</span> <span class="s1">&#39;yzafpnum kMGTPEZY&#39;</span><span class="p">[</span><span class="n">i</span> <span class="o">+</span> <span class="mi">8</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">s</span></div>


<div class="viewcode-block" id="timeit"><a class="viewcode-back" href="../../api.html#ib_insync.ib.timeit">[docs]</a><span class="k">class</span> <span class="nc">timeit</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;Context manager for timing.&quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="s1">&#39;Run&#39;</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">title</span> <span class="o">=</span> <span class="n">title</span>

    <span class="k">def</span> <span class="fm">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">t0</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>

    <span class="k">def</span> <span class="fm">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">_args</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">title</span> <span class="o">+</span> <span class="s1">&#39; took &#39;</span> <span class="o">+</span> <span class="n">formatSI</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="bp">self</span><span class="o">.</span><span class="n">t0</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39;s&#39;</span><span class="p">)</span></div>


<div class="viewcode-block" id="run"><a class="viewcode-back" href="../../api.html#ib_insync.ib.run">[docs]</a><span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="o">*</span><span class="n">awaitables</span><span class="p">:</span> <span class="n">Awaitable</span><span class="p">,</span> <span class="n">timeout</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="kc">None</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    By default run the event loop forever.</span>

<span class="sd">    When awaitables (like Tasks, Futures or coroutines) are given then</span>
<span class="sd">    run the event loop until each has completed and return their results.</span>

<span class="sd">    An optional timeout (in seconds) can be given that will raise</span>
<span class="sd">    asyncio.TimeoutError if the awaitables are not ready within the</span>
<span class="sd">    timeout period.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">awaitables</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">loop</span><span class="o">.</span><span class="n">is_running</span><span class="p">():</span>
            <span class="k">return</span>
        <span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
        <span class="n">result</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">version_info</span> <span class="o">&gt;=</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">7</span><span class="p">):</span>
            <span class="n">all_tasks</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">all_tasks</span><span class="p">(</span><span class="n">loop</span><span class="p">)</span>  <span class="c1"># type: ignore</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">all_tasks</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Task</span><span class="o">.</span><span class="n">all_tasks</span><span class="p">()</span>  <span class="c1"># type: ignore</span>
        <span class="k">if</span> <span class="n">all_tasks</span><span class="p">:</span>
            <span class="c1"># cancel pending tasks</span>
            <span class="n">f</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span><span class="o">*</span><span class="n">all_tasks</span><span class="p">)</span>
            <span class="n">f</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
            <span class="k">except</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">CancelledError</span><span class="p">:</span>
                <span class="k">pass</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">awaitables</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
            <span class="n">future</span> <span class="o">=</span> <span class="n">awaitables</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span><span class="o">*</span><span class="n">awaitables</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">timeout</span><span class="p">:</span>
            <span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait_for</span><span class="p">(</span><span class="n">future</span><span class="p">,</span> <span class="n">timeout</span><span class="p">)</span>
        <span class="n">task</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="n">future</span><span class="p">)</span>

        <span class="k">def</span> <span class="nf">onError</span><span class="p">(</span><span class="n">_</span><span class="p">):</span>
            <span class="n">task</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span>

        <span class="n">globalErrorEvent</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">onError</span><span class="p">)</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">result</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
        <span class="k">except</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">CancelledError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
            <span class="k">raise</span> <span class="n">globalErrorEvent</span><span class="o">.</span><span class="n">value</span><span class="p">()</span> <span class="ow">or</span> <span class="n">e</span>
        <span class="k">finally</span><span class="p">:</span>
            <span class="n">globalErrorEvent</span><span class="o">.</span><span class="n">disconnect</span><span class="p">(</span><span class="n">onError</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">result</span></div>


<span class="k">def</span> <span class="nf">_fillDate</span><span class="p">(</span><span class="n">time</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">time_</span><span class="p">,</span> <span class="n">datetime</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="n">datetime</span><span class="p">:</span>
    <span class="c1"># use today if date is absent</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">time</span><span class="p">,</span> <span class="n">time_</span><span class="p">):</span>
        <span class="n">dt</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">combine</span><span class="p">(</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">(),</span> <span class="n">time</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">dt</span> <span class="o">=</span> <span class="n">time</span>
    <span class="k">return</span> <span class="n">dt</span>


<div class="viewcode-block" id="schedule"><a class="viewcode-back" href="../../api.html#ib_insync.ib.schedule">[docs]</a><span class="k">def</span> <span class="nf">schedule</span><span class="p">(</span>
        <span class="n">time</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">time_</span><span class="p">,</span> <span class="n">datetime</span><span class="p">],</span> <span class="n">callback</span><span class="p">:</span> <span class="n">Callable</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Schedule the callback to be run at the given time with</span>
<span class="sd">    the given arguments.</span>
<span class="sd">    This will return the Event Handle.</span>

<span class="sd">    Args:</span>
<span class="sd">        time: Time to run callback. If given as :py:class:`datetime.time`</span>
<span class="sd">            then use today as date.</span>
<span class="sd">        callback: Callable scheduled to run.</span>
<span class="sd">        args: Arguments for to call callback with.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">dt</span> <span class="o">=</span> <span class="n">_fillDate</span><span class="p">(</span><span class="n">time</span><span class="p">)</span>
    <span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">(</span><span class="n">dt</span><span class="o">.</span><span class="n">tzinfo</span><span class="p">)</span>
    <span class="n">delay</span> <span class="o">=</span> <span class="p">(</span><span class="n">dt</span> <span class="o">-</span> <span class="n">now</span><span class="p">)</span><span class="o">.</span><span class="n">total_seconds</span><span class="p">()</span>
    <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">loop</span><span class="o">.</span><span class="n">call_later</span><span class="p">(</span><span class="n">delay</span><span class="p">,</span> <span class="n">callback</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span></div>


<div class="viewcode-block" id="sleep"><a class="viewcode-back" href="../../api.html#ib_insync.ib.sleep">[docs]</a><span class="k">def</span> <span class="nf">sleep</span><span class="p">(</span><span class="n">secs</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.02</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Wait for the given amount of seconds while everything still keeps</span>
<span class="sd">    processing in the background. Never use time.sleep().</span>

<span class="sd">    Args:</span>
<span class="sd">        secs (float): Time in seconds to wait.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">run</span><span class="p">(</span><span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">secs</span><span class="p">))</span>
    <span class="k">return</span> <span class="kc">True</span></div>


<div class="viewcode-block" id="timeRange"><a class="viewcode-back" href="../../api.html#ib_insync.ib.timeRange">[docs]</a><span class="k">def</span> <span class="nf">timeRange</span><span class="p">(</span>
        <span class="n">start</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">time_</span><span class="p">,</span> <span class="n">datetime</span><span class="p">],</span>
        <span class="n">end</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">time_</span><span class="p">,</span> <span class="n">datetime</span><span class="p">],</span>
        <span class="n">step</span><span class="p">:</span> <span class="nb">float</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Iterator</span><span class="p">[</span><span class="n">datetime</span><span class="p">]:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Iterator that waits periodically until certain time points are</span>
<span class="sd">    reached while yielding those time points.</span>

<span class="sd">    Args:</span>
<span class="sd">        start: Start time, can be specified as datetime.datetime,</span>
<span class="sd">            or as datetime.time in which case today is used as the date</span>
<span class="sd">        end: End time, can be specified as datetime.datetime,</span>
<span class="sd">            or as datetime.time in which case today is used as the date</span>
<span class="sd">        step (float): The number of seconds of each period</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">assert</span> <span class="n">step</span> <span class="o">&gt;</span> <span class="mi">0</span>
    <span class="n">delta</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">seconds</span><span class="o">=</span><span class="n">step</span><span class="p">)</span>
    <span class="n">t</span> <span class="o">=</span> <span class="n">_fillDate</span><span class="p">(</span><span class="n">start</span><span class="p">)</span>
    <span class="n">tz</span> <span class="o">=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">utc</span> <span class="k">if</span> <span class="n">t</span><span class="o">.</span><span class="n">tzinfo</span> <span class="k">else</span> <span class="kc">None</span>
    <span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">(</span><span class="n">tz</span><span class="p">)</span>
    <span class="k">while</span> <span class="n">t</span> <span class="o">&lt;</span> <span class="n">now</span><span class="p">:</span>
        <span class="n">t</span> <span class="o">+=</span> <span class="n">delta</span>
    <span class="k">while</span> <span class="n">t</span> <span class="o">&lt;=</span> <span class="n">_fillDate</span><span class="p">(</span><span class="n">end</span><span class="p">):</span>
        <span class="n">waitUntil</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
        <span class="k">yield</span> <span class="n">t</span>
        <span class="n">t</span> <span class="o">+=</span> <span class="n">delta</span></div>


<div class="viewcode-block" id="waitUntil"><a class="viewcode-back" href="../../api.html#ib_insync.ib.waitUntil">[docs]</a><span class="k">def</span> <span class="nf">waitUntil</span><span class="p">(</span><span class="n">t</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">time_</span><span class="p">,</span> <span class="n">datetime</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Wait until the given time t is reached.</span>

<span class="sd">    Args:</span>
<span class="sd">        t: The time t can be specified as datetime.datetime,</span>
<span class="sd">            or as datetime.time in which case today is used as the date.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">tzinfo</span><span class="p">)</span>
    <span class="n">secs</span> <span class="o">=</span> <span class="p">(</span><span class="n">_fillDate</span><span class="p">(</span><span class="n">t</span><span class="p">)</span> <span class="o">-</span> <span class="n">now</span><span class="p">)</span><span class="o">.</span><span class="n">total_seconds</span><span class="p">()</span>
    <span class="n">run</span><span class="p">(</span><span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">secs</span><span class="p">))</span>
    <span class="k">return</span> <span class="kc">True</span></div>


<div class="viewcode-block" id="timeRangeAsync"><a class="viewcode-back" href="../../api.html#ib_insync.ib.timeRangeAsync">[docs]</a><span class="k">async</span> <span class="k">def</span> <span class="nf">timeRangeAsync</span><span class="p">(</span>
        <span class="n">start</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">time_</span><span class="p">,</span> <span class="n">datetime</span><span class="p">],</span>
        <span class="n">end</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">time_</span><span class="p">,</span> <span class="n">datetime</span><span class="p">],</span>
        <span class="n">step</span><span class="p">:</span> <span class="nb">float</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">AsyncIterator</span><span class="p">[</span><span class="n">datetime</span><span class="p">]:</span>
    <span class="sd">&quot;&quot;&quot;Async version of :meth:`timeRange`.&quot;&quot;&quot;</span>
    <span class="k">assert</span> <span class="n">step</span> <span class="o">&gt;</span> <span class="mi">0</span>
    <span class="n">delta</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">seconds</span><span class="o">=</span><span class="n">step</span><span class="p">)</span>
    <span class="n">t</span> <span class="o">=</span> <span class="n">_fillDate</span><span class="p">(</span><span class="n">start</span><span class="p">)</span>
    <span class="n">tz</span> <span class="o">=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">utc</span> <span class="k">if</span> <span class="n">t</span><span class="o">.</span><span class="n">tzinfo</span> <span class="k">else</span> <span class="kc">None</span>
    <span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">(</span><span class="n">tz</span><span class="p">)</span>
    <span class="k">while</span> <span class="n">t</span> <span class="o">&lt;</span> <span class="n">now</span><span class="p">:</span>
        <span class="n">t</span> <span class="o">+=</span> <span class="n">delta</span>
    <span class="k">while</span> <span class="n">t</span> <span class="o">&lt;=</span> <span class="n">_fillDate</span><span class="p">(</span><span class="n">end</span><span class="p">):</span>
        <span class="k">await</span> <span class="n">waitUntilAsync</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
        <span class="k">yield</span> <span class="n">t</span>
        <span class="n">t</span> <span class="o">+=</span> <span class="n">delta</span></div>


<div class="viewcode-block" id="waitUntilAsync"><a class="viewcode-back" href="../../api.html#ib_insync.ib.waitUntilAsync">[docs]</a><span class="k">async</span> <span class="k">def</span> <span class="nf">waitUntilAsync</span><span class="p">(</span><span class="n">t</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">time_</span><span class="p">,</span> <span class="n">datetime</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;Async version of :meth:`waitUntil`.&quot;&quot;&quot;</span>
    <span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">tzinfo</span><span class="p">)</span>
    <span class="n">secs</span> <span class="o">=</span> <span class="p">(</span><span class="n">_fillDate</span><span class="p">(</span><span class="n">t</span><span class="p">)</span> <span class="o">-</span> <span class="n">now</span><span class="p">)</span><span class="o">.</span><span class="n">total_seconds</span><span class="p">()</span>
    <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">secs</span><span class="p">)</span>
    <span class="k">return</span> <span class="kc">True</span></div>


<div class="viewcode-block" id="patchAsyncio"><a class="viewcode-back" href="../../api.html#ib_insync.ib.patchAsyncio">[docs]</a><span class="k">def</span> <span class="nf">patchAsyncio</span><span class="p">():</span>
    <span class="sd">&quot;&quot;&quot;Patch asyncio to allow nested event loops.&quot;&quot;&quot;</span>
    <span class="kn">import</span> <span class="nn">nest_asyncio</span>
    <span class="n">nest_asyncio</span><span class="o">.</span><span class="n">apply</span><span class="p">()</span></div>


<div class="viewcode-block" id="startLoop"><a class="viewcode-back" href="../../api.html#ib_insync.ib.startLoop">[docs]</a><span class="k">def</span> <span class="nf">startLoop</span><span class="p">():</span>
    <span class="sd">&quot;&quot;&quot;Use nested asyncio event loop for Jupyter notebooks.&quot;&quot;&quot;</span>
    <span class="n">patchAsyncio</span><span class="p">()</span></div>


<div class="viewcode-block" id="useQt"><a class="viewcode-back" href="../../api.html#ib_insync.ib.useQt">[docs]</a><span class="k">def</span> <span class="nf">useQt</span><span class="p">(</span><span class="n">qtLib</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;PyQt5&#39;</span><span class="p">,</span> <span class="n">period</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.01</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Run combined Qt5/asyncio event loop.</span>

<span class="sd">    Args:</span>
<span class="sd">        qtLib: Name of Qt library to use:</span>

<span class="sd">          * PyQt5</span>
<span class="sd">          * PyQt6</span>
<span class="sd">          * PySide2</span>
<span class="sd">          * PySide6</span>
<span class="sd">        period: Period in seconds to poll Qt.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="nf">qt_step</span><span class="p">():</span>
        <span class="n">loop</span><span class="o">.</span><span class="n">call_later</span><span class="p">(</span><span class="n">period</span><span class="p">,</span> <span class="n">qt_step</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">stack</span><span class="p">:</span>
            <span class="n">qloop</span> <span class="o">=</span> <span class="n">qc</span><span class="o">.</span><span class="n">QEventLoop</span><span class="p">()</span>
            <span class="n">timer</span> <span class="o">=</span> <span class="n">qc</span><span class="o">.</span><span class="n">QTimer</span><span class="p">()</span>
            <span class="n">timer</span><span class="o">.</span><span class="n">timeout</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">qloop</span><span class="o">.</span><span class="n">quit</span><span class="p">)</span>
            <span class="n">stack</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">qloop</span><span class="p">,</span> <span class="n">timer</span><span class="p">))</span>
        <span class="n">qloop</span><span class="p">,</span> <span class="n">timer</span> <span class="o">=</span> <span class="n">stack</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
        <span class="n">timer</span><span class="o">.</span><span class="n">start</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
        <span class="n">qloop</span><span class="o">.</span><span class="n">exec</span><span class="p">()</span> <span class="k">if</span> <span class="n">qtLib</span> <span class="o">==</span> <span class="s1">&#39;PyQt6&#39;</span> <span class="k">else</span> <span class="n">qloop</span><span class="o">.</span><span class="n">exec_</span><span class="p">()</span>
        <span class="n">timer</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>
        <span class="n">stack</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">qloop</span><span class="p">,</span> <span class="n">timer</span><span class="p">))</span>
        <span class="n">qApp</span><span class="o">.</span><span class="n">processEvents</span><span class="p">()</span>

    <span class="k">if</span> <span class="n">qtLib</span> <span class="ow">not</span> <span class="ow">in</span> <span class="p">(</span><span class="s1">&#39;PyQt5&#39;</span><span class="p">,</span> <span class="s1">&#39;PyQt6&#39;</span><span class="p">,</span> <span class="s1">&#39;PySide2&#39;</span><span class="p">,</span> <span class="s1">&#39;PySide6&#39;</span><span class="p">):</span>
        <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Unknown Qt library: </span><span class="si">{</span><span class="n">qtLib</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="kn">from</span> <span class="nn">importlib</span> <span class="kn">import</span> <span class="n">import_module</span>
    <span class="n">qc</span> <span class="o">=</span> <span class="n">import_module</span><span class="p">(</span><span class="n">qtLib</span> <span class="o">+</span> <span class="s1">&#39;.QtCore&#39;</span><span class="p">)</span>
    <span class="n">qw</span> <span class="o">=</span> <span class="n">import_module</span><span class="p">(</span><span class="n">qtLib</span> <span class="o">+</span> <span class="s1">&#39;.QtWidgets&#39;</span><span class="p">)</span>
    <span class="k">global</span> <span class="n">qApp</span>
    <span class="n">qApp</span> <span class="o">=</span> <span class="p">(</span><span class="n">qw</span><span class="o">.</span><span class="n">QApplication</span><span class="o">.</span><span class="n">instance</span><span class="p">()</span>     <span class="c1"># type: ignore</span>
            <span class="ow">or</span> <span class="n">qw</span><span class="o">.</span><span class="n">QApplication</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">))</span>  <span class="c1"># type: ignore</span>
    <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
    <span class="n">stack</span><span class="p">:</span> <span class="nb">list</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">qt_step</span><span class="p">()</span></div>


<div class="viewcode-block" id="formatIBDatetime"><a class="viewcode-back" href="../../api.html#ib_insync.ib.formatIBDatetime">[docs]</a><span class="k">def</span> <span class="nf">formatIBDatetime</span><span class="p">(</span><span class="n">dt</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">date</span><span class="p">,</span> <span class="n">datetime</span><span class="p">,</span> <span class="nb">str</span><span class="p">,</span> <span class="kc">None</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;Format date or datetime to string that IB uses.&quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">dt</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">dt</span><span class="p">,</span> <span class="n">datetime</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">dt</span><span class="o">.</span><span class="n">tzinfo</span><span class="p">:</span>
            <span class="c1"># convert to local system timezone</span>
            <span class="n">dt</span> <span class="o">=</span> <span class="n">dt</span><span class="o">.</span><span class="n">astimezone</span><span class="p">()</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">dt</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;%Y%m</span><span class="si">%d</span><span class="s1"> %H:%M:%S&#39;</span><span class="p">)</span>
    <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">dt</span><span class="p">,</span> <span class="n">date</span><span class="p">):</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">dt</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;%Y%m</span><span class="si">%d</span><span class="s1"> 23:59:59&#39;</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">dt</span>
    <span class="k">return</span> <span class="n">s</span></div>


<div class="viewcode-block" id="parseIBDatetime"><a class="viewcode-back" href="../../api.html#ib_insync.ib.parseIBDatetime">[docs]</a><span class="k">def</span> <span class="nf">parseIBDatetime</span><span class="p">(</span><span class="n">s</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Union</span><span class="p">[</span><span class="n">date</span><span class="p">,</span> <span class="n">datetime</span><span class="p">]:</span>
    <span class="sd">&quot;&quot;&quot;Parse string in IB date or datetime format to datetime.&quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="o">==</span> <span class="mi">8</span><span class="p">:</span>
        <span class="c1"># YYYYmmdd</span>
        <span class="n">y</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="mi">4</span><span class="p">])</span>
        <span class="n">m</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="mi">4</span><span class="p">:</span><span class="mi">6</span><span class="p">])</span>
        <span class="n">d</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="mi">6</span><span class="p">:</span><span class="mi">8</span><span class="p">])</span>
        <span class="n">dt</span> <span class="o">=</span> <span class="n">date</span><span class="p">(</span><span class="n">y</span><span class="p">,</span> <span class="n">m</span><span class="p">,</span> <span class="n">d</span><span class="p">)</span>
    <span class="k">elif</span> <span class="n">s</span><span class="o">.</span><span class="n">isdigit</span><span class="p">():</span>
        <span class="n">dt</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">fromtimestamp</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">),</span> <span class="n">timezone</span><span class="o">.</span><span class="n">utc</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="c1"># YYYYmmdd  HH:MM:SS</span>
        <span class="c1"># or</span>
        <span class="c1"># YYYY-mm-dd HH:MM:SS.0</span>
        <span class="n">ss</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">&#39; &#39;</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">&#39;-&#39;</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">)[:</span><span class="mi">16</span><span class="p">]</span>
        <span class="n">dt</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">strptime</span><span class="p">(</span><span class="n">ss</span><span class="p">,</span> <span class="s1">&#39;%Y%m</span><span class="si">%d</span><span class="s1">%H:%M:%S&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">dt</span></div>
</pre></div>

           </div>
          </div>
          <footer>

  <hr/>

  <div role="contentinfo">
    <p>&#169; Copyright 2021, Ewald de Wit.</p>
  </div>

  Built with <a href="https://www.sphinx-doc.org/">Sphinx</a> using a
    <a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
    provided by <a href="https://readthedocs.org">Read the Docs</a>.
   

</footer>
        </div>
      </div>
    </section>
  </div>
  <script>
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script> 

</body>
</html>